//
//  MCGoodsCategoryViewController.swift
//  StoreManage
//
//  Created by MC on 2018/9/11.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit


class MCGoodsCategoryViewController: MCViewController {
    
    
    private var isEditingStatus = false
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        sendNetworking()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
    }
    
    // MARK: - Setter & Getter
    private lazy var tableView: MCTableView = {
        let tableView = MCTableView()
        tableView.backgroundColor = UIColor.MCGray_light
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = 55
        return tableView
    }()
    
    lazy var dataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
    
    lazy var footerView: MCGoodsCategoryFooterView = {
        let view = MCGoodsCategoryFooterView()
        return view
    }()
    
    lazy var rightBarButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.titleLabel?.font = MCFont(14)
        button.frame = CGRect.init(x: 0, y: 0, width: 50, height: 40)
        button.setTitleColor(UIColor.MCWords, for: .normal)
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.right
        button.setTitle("排序", for: .normal)
        button.setTitle("取消", for: .selected)
        button.addTarget(self, action: #selector(rightItemClicked), for: .touchUpInside)
        return button
    }()
    
    lazy var bottomButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.titleLabel?.font = MCFont(14)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitle("添加分类", for: .normal)
        button.setTitle("保存排序", for: .selected)
        button.backgroundColor = UIColor.MCMain
        button.addTarget(self, action: #selector(bottomButtonClicked), for: .touchUpInside)
        return button
    }()
    
    lazy var promptLabel: MCLabel = {
        let label = MCLabel()
        label.font = MCFont(12)
        label.layer.cornerRadius = 14
        label.layer.masksToBounds = true
        label.layer.borderColor = UIColor.MCGray_middle.cgColor
        label.layer.borderWidth = 1
        label.textAlignment = NSTextAlignment.center
        label.textColor = UIColor.MCGray_middle
        let str = "手指按住拖动排序"
        label.attributedText = str.MCAttributedString_color(color: UIColor.MCMain, range: NSRange.init(location: 4, length: 2))
        return label
    }()
    
    

}


//MARK: 通知回调，闭包回调，点击事件
extension MCGoodsCategoryViewController {
    @objc func rightItemClicked() {
        
        rightBarButton.isSelected = !rightBarButton.isSelected
        
        bottomButton.isSelected = rightBarButton.isSelected
        
        isEditingStatus = rightBarButton.isSelected
        
        let height = isEditingStatus ? 28 : 0
        promptLabel.snp.remakeConstraints { (make) ->Void in
            make.centerX.equalTo(view)
            make.bottom.equalTo(bottomButton.snp.top).offset(-10)
            make.size.equalTo(CGSize.init(width: 120, height: height))
        }

        tableView.setEditing(isEditingStatus, animated: true)
        
        tableView.reloadData()
    }
    
    @objc func bottomButtonClicked() {
        
        if bottomButton.isSelected { // 保存排序
            saveSorting()
        } else {  // 添加分类
            let vc = MCAddGoodsCategoryViewController()
            vc.isNewGoodsCategory = true
            MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
        }
    }
    
    
    // 保存排序
    func saveSorting() {
        let arrayM = NSMutableArray()
        for model in dataArrayM {
            let tempModel = model as! MCGoodsCategoryModel
            arrayM.add(["selfCategoryId" : tempModel.selfCategoryId.intValue])
        }
        
        let para = [
            "categoryList" : arrayM
        ]
        MCNetwork.POST(JAVA_editCategoryOrderNo, para, success: { (data)
            in
            MCHUD_default(message: "保存成功", view: self.view, delay: 1.0)
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0, execute: {
                // 取消编辑状态
                self.rightItemClicked()
            })
        })
    }
}


//MARK: 网络请求
extension MCGoodsCategoryViewController {
    
    func sendNetworking() {
        MCNetwork.POST(JAVA_querySelfCategoryPage, success: { (data) in
            
            self.dataArrayM.removeAllObjects()
            
            let dataArray = data.arrayObject ?? []
            for dict in dataArray {
                let model = MCGoodsCategoryModel()
                model.setValuesForKeys(dict as? [String:Any] ?? [:])

                // 其他分类的id是-1. 从数组中拿掉，放尾部视图上
                if model.selfCategoryId.intValue == -1 {
                    self.footerView.model = model
                } else {
                    self.dataArrayM.add(model)
                }
            }
            self.tableView.reloadData()
        })
    }
}

//MARK: UI的处理,通知的接收
extension MCGoodsCategoryViewController {
    
    func baseSetting() {
        self.title = "商品分类"
        view.backgroundColor = UIColor.MCGray_light
        
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: rightBarButton)
    }
    
    
    func initUI() {
        
        view.addSubview(bottomButton)
        bottomButton.snp.remakeConstraints { (make) ->Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        view.addSubview(promptLabel)
        promptLabel.snp.remakeConstraints { (make) ->Void in
            make.centerX.equalTo(view)
            make.bottom.equalTo(bottomButton.snp.top).offset(-10)
            make.size.equalTo(CGSize.init(width: 120, height: 0))
        }
        
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) ->Void in
            make.left.right.top.equalTo(view)
            make.bottom.equalTo(promptLabel.snp.top).offset(-10)
        }
        
        tableView.tableFooterView = footerView
    }
}

//MARK: UITableViewDelegate,UITableViewDataSource
extension MCGoodsCategoryViewController: UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArrayM.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = MCGoodsCategoryCell.customCell(tableView: tableView)
        cell.isEditingStatus = isEditingStatus
        
        let model = dataArrayM[indexPath.row] as! MCGoodsCategoryModel
        
        cell.model = model
        
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       
        let model = dataArrayM[indexPath.row] as! MCGoodsCategoryModel
        
        let vc = MCAddGoodsCategoryViewController()
        vc.isNewGoodsCategory = false
        vc.model = model
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack:true)
    }
    
    // 移动
    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return isEditingStatus
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        return UITableViewCellEditingStyle.none
    }
    
    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        
        // 1.1 取出来原位置数据
        let model = dataArrayM[sourceIndexPath.row] as! MCGoodsCategoryModel
        
        // 1.2 移除原位置对象
        dataArrayM.removeObject(at: sourceIndexPath.row)
        
        // 1.3 加入到新的位置
        dataArrayM.insert(model, at: destinationIndexPath.row)
    }
}

